#! encoding=utf-8

import requests
from common import HOST, WS_HOST
import traceback
import websocket


def add(camera_id, group_id, attached_params):
    url = HOST + '/handle'
    print "POST /handle 创建 Handle ..."
    ret = None
    try:
        ret = requests.session().post(url, {'camera_id': camera_id, 'group_id': group_id, 'attached_params': attached_params}).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def get():
    url = HOST + '/handle'
    print "GET /handle 获取所有 Handle ..."
    ret = None
    try:
        ret = requests.session().get(url).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def delete(handle_id):
    url = HOST + '/handle/' + handle_id
    print "DELETE /handle/{handle_id} 删除单个 Handle ..."
    try:
        requests.session().delete(url)
    except:
        print traceback.format_exc()


def getHandle(handle_id):
    url = HOST + '/handle/' + handle_id
    print "GET /handle/{handle_id} 获取单个 Handle ..."
    ret = None
    try:
        ret = requests.session().get(url).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def update(handle_id, camera_id, group_id, attached_params):
    url = HOST + '/handle/' + handle_id
    print "PUT /handle/{handle_id} 修改单个 Handle ..."
    ret = None
    try:
        ret = requests.session().put(url, {'camera_id': camera_id, 'group_id': group_id, 'attached_params': attached_params}).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def start(handle_id):
    url = HOST + '/handle/' + handle_id + 'start'
    print "POST /handle/{handle_id}/start 打开 Handle ..."
    try:
        requests.session().post(url)
    except:
        print traceback.format_exc()


def stop(handle_id):
    url = HOST + '/handle/' + handle_id + 'stop'
    print "POST /handle/{handle_id}/stop 停止 Handle ..."
    try:
        requests.session().post(url)
    except:
        print traceback.format_exc()


def live(handle_id):

    def on_message(ws, message):
        print '### message ###', message

    def on_error(ws, error):
        print '### error ###', error

    def on_close(ws):
        print '### closed ###'

    def on_open(ws):
        print '### open ###'

    url = WS_HOST + '/handle/' + handle_id + '/live'
    print url
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(url,
                               on_open = on_open,
                               on_message = on_message,
                               on_error = on_error,
                               on_close = on_close)
    ws.run_forever()